package l1j.opqlo.自動發放;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.NewSystem.A_ColorMessage;
import l1j.opqlo.NewSystem.各項記錄輸出;
import l1j.server.DatabaseFactory;
import l1j.server.server.datatables.CharObjidTable;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1Item;
import l1j.server.server.utils.SQLUtil;

public class 推文物品 {

	private static final Logger _log = Logger.getLogger(推文發放.class.getName());

	private static L1ItemInstance createNewItem(final L1PcInstance pc,final int itemid,final int count , final int enchantlv , final int bless , final int isid) {
		final L1ItemInstance item = ItemTable.getInstance().createItem(itemid);
		if (item != null) {
			item.setCount(count);
			if (pc.getInventory().checkAddItem(item, count) == L1Inventory.OK) {
				item.setEnchantLevel(enchantlv);
				item.setBless(bless);
				item.setIdentified(isid ==1 ? true : false);
				pc.getInventory().storeItem(item);
			} else { // 持てない場合は地面に落とす 處理のキャンセルはしない（不正防止）
				//				L1World.getInstance().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(item);
				return null;
			}
			pc.sendPackets(new S_ServerMessage(403, item.getLogName())); // %0を手に入れました。
			return item;
		} else {
			return null;
		}
	}
	private static void deleteDate(final int objid){

		final String name = CharObjidTable.get().isChar(objid);

		if(name ==null){
			return;
		}
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("DELETE FROM Z_opqlo_推文發放 WHERE 玩家名稱=? && 已加載=1");
			pstm.setString(1, name);
			pstm.execute();
		} catch (final SQLException e) {
			_log.log(Level.SEVERE, "ブックマークの削除でエラーが発生しました。", e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	private final Map<Integer,int[]>_itemList = new HashMap<Integer , int[]>();


	private  final int _objid;


	public 推文物品(final int id){
		this._objid = id;
	}

	public void addItem(final int itemId , final int count , final int enchantlv , final int bless , final int isid){

		final int[] value =  new int[4];
		value[0] = count;
		value[1] = enchantlv;
		value[2] = bless;
		value[3] = isid;
		this._itemList.put(new Integer(itemId), value);
	}

	public void start(final L1PcInstance tgpc){
		final Set<Integer>_keyList =this._itemList.keySet();
		if(_keyList.isEmpty()){
			return;
		}
		final StringBuilder msg =new StringBuilder()
		.append("IP(").append(tgpc.getNetConnection().getIp().toString()).append(") 玩家:[ ").append(tgpc.getName())
		.append(" ]時間: ").append(new Timestamp(System.currentTimeMillis()));

		for(final int key : _keyList){
			final int[] value = this._itemList.get(key);
			final int count = value[0];
			final int enchantlv = value[1];
			final int bless = value[2];
			final int isid = value[3];
			final L1Item itemTemplate = ItemTable.getInstance().getTemplate(key);
			if(itemTemplate == null){
				this._itemList.remove(key);
				continue;
			}
			if(itemTemplate.isStackable()){
				final L1ItemInstance newitem =	createNewItem(tgpc , key, count, enchantlv, bless, isid);
				if(newitem == null){
					this._itemList.remove(key);
					break;
				}
				tgpc.sendPackets(new A_ColorMessage( 1 , "推文獎勵已發放，獲得【"+newitem.getLogName()+"】。"));
				msg.append("領取獎勵[ ").append(newitem.getViewName()).append("]	流水號:	").append(newitem.getId()).append("	\r\n");

			}else {
				if(count>1){
					for(int i =count; i>0; i--){
						final L1ItemInstance newitem =	createNewItem(tgpc , key, 1, enchantlv, bless, isid);
						if(newitem == null){
							this._itemList.remove(key);
							break;
						}
						tgpc.sendPackets(new A_ColorMessage( 1 , "推文獎勵已發放，獲得【"+newitem.getLogName()+"】。"));
						msg.append("領取獎勵[ ").append(newitem.getViewName()).append("]	流水號:	").append(newitem.getId()).append("	\r\n");
					}
				}else{
					final L1ItemInstance newitem =	createNewItem(tgpc , key, 1, enchantlv, bless, isid);
					if(newitem == null){
						this._itemList.remove(key);
						break;
					}
					tgpc.sendPackets(new A_ColorMessage( 1 , "推文獎勵已發放，獲得【"+newitem.getLogName()+"】。"));
					msg.append("領取獎勵[ ").append(newitem.getViewName()).append("]	流水號:	").append(newitem.getId()).append("	\r\n");
				}
			}
		}
		各項記錄輸出.LogSave(18, msg.toString());
		msg.delete(0, msg.length());
		deleteDate(this._objid);
		this._itemList.clear();
	}
}
